﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Linq;
using Sipek.Common;


namespace SoftPhone
{
    public partial class frmMain : XtraForm
    {
        private System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        private SIPManager manager = new SIPManager();
        private delegate void ReFreshForm();
        private int _sessionid;
        public frmMain()
        {
            InitializeComponent();
            InitialLogin();
            InitialLaunch();
        }
        
        private void InComingCallHandle(string number)
        {
            DialogResult result = MessageBox.Show("Cuộc gọi đến từ: " + number + "\n"+ "Nhận cuộc gọi này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (result == DialogResult.Yes)
            {                
                manager.AnswerCall(number);
            }
            else
            {
                manager.ReleaseCall(number);
            }
        }

        private void InitialLogin()
        {
            string message = "";
            SIPManager.OnAccountChangedNotification = new SIPManager.OnAccountChanged(AccountChangedEvent);
            manager.InitalLogin(ref message);
            if (message != "")
            {
                MessageBox.Show(message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void InitialLaunch()
        {            
            SIPManager.IncomingCallNotification = new SIPManager.IncomingCallHandle(InComingCallHandle);
            SIPManager.CallStateNotification = new SIPManager.CallStateChanged(CallStateHanle);            
            this.Height = 330;
            this.spcontain.Panel1Collapsed = true;
            timer.Tick += new EventHandler(UpdateTimeOut);
            timer.Interval = 1000;
        }

        private void AccountChangedEvent(string UserName)
        {
            this.Text = "Blue Phone - " + UserName;
        }

        private void CallStateHanle(int sessionid)
        {
            _sessionid = sessionid;            
            EnableButton();
            RefreshHoldButton();
            if (InvokeRequired)
                this.BeginInvoke(new ReFreshForm(this.RunCounter));
            else
                RunCounter();
        }

        private void RefreshHoldButton()
        {
            if (btnHold.InvokeRequired)
            {
                btnHold.Invoke(new MethodInvoker(RefreshHoldButton));
            }
            else
            {
                if (SIPManager.CallManager.getCall(_sessionid).StateId != EStateId.HOLDING)
                {
                    btnHold.Text = "Giữ máy";
                }
            }
        }


        private void EnableButton()
        {
            if (btnCall.InvokeRequired)
            {
                btnCall.Invoke(new MethodInvoker(EnableButton));
            }
            else
            {
                if (SIPManager.CallManager.getCall(_sessionid).StateId != EStateId.NULL)
                {
                    btnCall.Enabled = false;
                    txtNumber.Text = "";
                }
                else
                {
                    btnCall.Enabled = true;
                }
            }
        }

        private void UpdateTimeOut(object sender, EventArgs e)
        {
            RefreshCounter();
        }

        private void RefreshCounter()
        {
            if (lblTimer.InvokeRequired)
            {
                lblTimer.Invoke(new MethodInvoker(Refresh));
            }
            else
            { 
                var callstate = SIPManager.CallManager.getCall(_sessionid);
                if (callstate.StateId == EStateId.ACTIVE || callstate.StateId == EStateId.HOLDING)
                {
                    this.Height = 370;
                    this.spcontain.Panel1Collapsed = false;
                    this.lblConnectedNumber.Text = callstate.CallingNumber;
                    lblTimer.Text = callstate.RuntimeDuration.ToString().Remove(callstate.RuntimeDuration.ToString().IndexOf('.'));
                }
                else
                {
                    this.Height = 330;
                    lblTimer.Text = "lblTimer";
                    this.lblConnectedNumber.Text = "lblConnectedNumber";
                    this.spcontain.Panel1Collapsed = true;
                }
            }            
        }

        private void RunCounter()
        {            
            timer.Start();
        }

        #region SettingButton
        private void accountToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Account_info f = new Account_info();
            f.ShowDialog();
        }

        private void settingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmDeviceSetting f = new frmDeviceSetting();
            f.ShowDialog();
        }
        #endregion

        #region NumberButton
        private void btnnumber1_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "1";
        }

        private void btnnumber2_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "2";
        }

        private void btnnumber3_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "3";
        }

        private void btnnumber4_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "4";
        }

        private void btnnumber5_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "5";
        }

        private void btnnumber6_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "6";
        }

        private void btnnumber7_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "7";
        }

        private void btnnumber8_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "8";
        }
        private void btnnumber9_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "9";
        }
        private void btnnumber0_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "0";
        }

        private void btnStar_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "*";
        }

        private void btnSharp_Click(object sender, EventArgs e)
        {
            txtNumber.Text += "#";
        }
        #endregion

        #region OpeationCallButon
        private void btnCall_Click(object sender, EventArgs e)
        {
            string message = "";
            if (SIPManager.CallManager.IsInitialized == true)
            {
                manager.CreateOutBoundCall(txtNumber.Text, ref message);
                if (message != "")
                {
                    MessageBox.Show(message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            { 
                var config = PolicyConfigClient.ReadConfig("Account");
                if (config != null)
                {
                    string yealinkip = config.Where(a => a.Key == "YealinkIp").SingleOrDefault().Value;
                    string callserver = config.Where(a => a.Key == "CallServerIp").SingleOrDefault().Value;
                    string extension = config.Where(a => a.Key == "YealinkExtension").SingleOrDefault().Value;
                    string outcallnumber = txtNumber.Text.Trim();
                    string actionuri = YealinkControl.CreateOutBoundActionUri(yealinkip, extension, outcallnumber, callserver);
                    YealinkControl.SendAction(actionuri, ref message);
                    if (message != "")
                    {
                        MessageBox.Show(message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            txtNumber.Text = "";
        }        

        private void btnHangUp_Click(object sender, EventArgs e)
        {
            if(SIPManager.CallManager.getCall(_sessionid).StateId != EStateId.NULL)
            {
                manager.ReleaseCall(SIPManager.CallManager.getCall(_sessionid).CallingNumber);
                return;
            }
        }

        private void btnTransfer_Click(object sender, EventArgs e)
        {
            if (SIPManager.CallManager.getCall(_sessionid).StateId != EStateId.NULL)
            {
                frmTransferCall frm = new frmTransferCall();
                frm.ShowDialog();
            }
        }        

        private void btnHold_Click(object sender, EventArgs e)
        {
            if (SIPManager.CallManager.getCall(_sessionid).StateId == EStateId.ACTIVE)
            {
                btnHold.Text = "Nhả máy";
                manager.HoldorRetrieveCall();
            }
            else if (SIPManager.CallManager.getCall(_sessionid).StateId == EStateId.HOLDING)
            {
                btnHold.Text = "Giữ máy";
                manager.HoldorRetrieveCall();
            }
        }
        #endregion

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void yealinkToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmYealinkSetting frm = new frmYealinkSetting();
            frm.ShowDialog();
        }

        private void cbxSoftPhone_Click(object sender, EventArgs e)
        {
            cbxYeaLinkPhone.Checked = false;
        }

        private void cbxYeaLinkPhone_Click(object sender, EventArgs e)
        {
            cbxSoftPhone.Checked = false;
        }

        private void cbxYeaLinkPhone_CheckStateChanged(object sender, EventArgs e)
        {
            if (cbxYeaLinkPhone.CheckState == CheckState.Checked)
            {
                YealinkControl.IsInitialize = true;
                var config = PolicyConfigClient.ReadConfig("Account");
                if (config != null)
                {
                    YealinkConfig yealink = new YealinkConfig()
                    {
                        Account = config.Where(a => a.Key == "YealinkUserName").SingleOrDefault().Value,
                        Password = config.Where(a => a.Key == "YealinkPassword").SingleOrDefault().Value,
                        Extension = config.Where(a => a.Key == "YealinkExtension").SingleOrDefault().Value,
                        YealinkIp = config.Where(a => a.Key == "YealinkIp").SingleOrDefault().Value,
                        CallServerIp = config.Where(a => a.Key == "CallServerIp").SingleOrDefault().Value,
                    };
                }
            }
            else if (cbxYeaLinkPhone.CheckState == CheckState.Unchecked)
            {
                YealinkControl.IsInitialize = false;
            }
        }

        private void cbxSoftPhone_CheckStateChanged(object sender, EventArgs e)
        {
            if (cbxSoftPhone.CheckState == CheckState.Checked)
            {                
                InitialLogin();
            }
            else if (cbxSoftPhone.CheckState == CheckState.Unchecked)
            {
                if (SIPManager.CallManager.IsInitialized)
                {
                    SIPManager.CallManager.Shutdown();
                }
            }
        }

    }
}